<template>
    <el-form label-width="100px" size="small" v-loading="submitLoading">
        <el-row :gutter="10">
            <h4>商品属性 <span class="font-size--sm text-gray font-weight--sm"><i class="el-icon-warning"></i> 商品属性最多可以选择6个，自定义属性最多可以设置6个。</span></h4>
            <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
                <el-form-item label="商品属性">
                    <el-select size="small" v-model="choosePropertyDataList" multiple :multiple-limit="maxAttrLength" filterable placeholder="请选择商品属性" value-key="name" @change="changeOption">
                        <el-option v-for="item in checkPropertyDataList" :key="item.id" :label="item.name" :value="item" :disabled="item.status == 0"></el-option>
                    </el-select>
                    <el-table :data="choosePropertyDataList" border class="margin_top_20 width_1000">
                        <el-table-column prop="name" label="属性名"></el-table-column>
                        <el-table-column prop="children" label="属性值">
                            <template slot-scope="scope">
                                <div class="text-ellipsis">
                                    <span v-for="(childItem, childIndex) of scope.row.children" :key="'propertyChild' + childIndex">{{childItem.name}}<span v-if="childIndex < scope.row.children.length - 1">、</span></span>
                                </div>
                            </template>
                        </el-table-column>
                        <el-table-column prop="address" label="操作">
                            <template slot-scope="scope">
                                <label class="text-blue pointer" @click="addPropertyChild(scope.row)">添加</label>
                                <el-link type="danger" :underline="false" @click="isChangeAttr = true;removeProperty(scope.$index)" class="margin_left_10">删除</el-link>
                            </template>
                        </el-table-column>
                    </el-table>
                    <div><el-checkbox v-model="isCustom" :disabled="!isCustom && canBuildAttrLength == 0">添加自定义属性</el-checkbox></div>
                    <div class="custom_attribute width_1000" v-if="isCustom">
                        <div class="custom_attribute__item" v-for="(customItem, customIndex) of myCustomPropertyDataList" :key="'customproperty' + customIndex">
                            <el-row :gutter="10">
                                <el-col :xs="6" :sm="3" :md="3" :lg="3" :xl="3">属性名</el-col>
                                <el-col :xs="18" :sm="9" :md="9" :lg="9" :xl="9">
                                    <el-input size="small" v-model="customItem.name" placeholder="请输入属性名" maxlength="10" show-word-limit></el-input>
                                </el-col>
                                <el-col :xs="6" :sm="3" :md="3" :lg="3" :xl="3">属性编码</el-col>
                                <el-col :xs="18" :sm="9" :md="9" :lg="9" :xl="9">
                                    <el-input size="small" v-model="customItem.code" placeholder="请输入属性编码" maxlength="3" disabled show-word-limit  @keydown.native="inputUnpass" @input="inputSuppCode1($event, customItem)"></el-input>
                                </el-col>
                            </el-row>
                            <el-row :gutter="10">
                                <el-col :xs="6" :sm="3" :md="3" :lg="3" :xl="3">属性值</el-col>
                                <el-col :xs="18" :sm="21" :md="21" :lg="21" :xl="21">
                                    <el-table :data="customItem.children" border class="full-width margin_top_20">
                                        <el-table-column type="index" label="序号" width="60"></el-table-column>
                                        <el-table-column prop="date" label="属性值">
                                            <template slot-scope="scope">
                                                <el-input size="small" v-model="scope.row.name" placeholder="请输入属性值" maxlength="25" show-word-limit></el-input>
                                            </template>
                                        </el-table-column>
                                        <el-table-column prop="name" label="属性值编码">
                                            <template slot-scope="scope">
                                                <el-input size="small" v-model="scope.row.code" placeholder="请输入属性值编码" disabled maxlength="3" show-word-limit @keydown.native="inputUnpass" @input="inputSuppCode(scope)"></el-input>
                                            </template>
                                        </el-table-column>
                                        <el-table-column prop="address" label="操作">
                                            <template slot-scope="scope">
                                                <el-link type="danger" :underline="false" @click="removeOnePropertyValueItem(customIndex, scope.$index)">删除</el-link>
                                            </template>
                                        </el-table-column>
                                    </el-table>
                                    <div class="margin_top_10">
                                        <label class="text-blue pointer" @click="addOnePropertyValueItem(customIndex)">添加属性值</label><br>
                                        <el-button @click="saveOnePropertyItemCopy(customIndex)">保存</el-button>
                                        <el-button type="danger" @click="removeOnePropertyItem(customIndex)">删除</el-button>
                                    </div>
                                </el-col>
                            </el-row>
                        </div>
                    </div>
                    <div class="margin_top_10" v-show="isCustom && canBuildAttrLength > 0"><label class="text-blue pointer" @click="addOnePropertyItem()">添加属性</label></div>
                    <div class="margin_top_10"><el-button type="primary" @click="validIsCanGenerrate()">生成SKU</el-button></div>
                </el-form-item>
            </el-col>
        </el-row>
        <el-row :gutter="10">
            <h4>SKU信息</h4>
            <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
                <el-table :data="generateSKUDataList" v-loading="loading" class="full-width margin_top_20">
                    <el-table-column prop="skuNo" label="SKU编码" width="260">
                        <template slot-scope="scope">
                            <div class="flex align-center flex-start">
                                <div style="width: 100px">SKU编码：</div>
                                <div style="width: 140px">
                                    <div class="el-input el-input--small is-disabled">
                                        <div class="el-input__inner text-ellipsis" :title="scope.row.skuNo">{{scope.row.skuNo ? scope.row.skuNo : '自动生成SKU编码'}}</div>
                                    </div>
                                </div>
                            </div>
                            <div class="flex align-center flex-start margin_top_10">
                                <div style="width: 100px">商品条码：</div>
                                <div style="width: 140px">
                                    <el-input size="small" v-model.trim="scope.row.skuCode" placeholder="请输入商品条码" maxlength="30"></el-input>
                                </div>
                            </div>
                            <div class="flex align-center flex-start margin_top_10">
                                <div style="width: 100px">供货商货号：</div>
                                <div style="width: 140px">
                                    <el-input size="small" v-model.trim="scope.row.skuSupplyNo" placeholder="请输入供货商货号" maxlength="30"></el-input>
                                </div>
                            </div>
                            <div class="margin_top_10" v-if="scope.row.skuSupplyNo"><el-button size="mini" @click="copySkuSupplyNo(scope.$index)">复制供应商货号到全部SKU</el-button></div>
                        </template>
                    </el-table-column>
                    <el-table-column prop="skuImg" label="图片" width="200">
                        <template slot-scope="scope">
                            <app-uploader title="商品图片" :limit="1" :initFiles="scope.row.skuImg ? [scope.row.skuImg] : []" :accept="'image/*'" :fileFormat="fileFormat" @change="skuImgChange($event, scope.$index)"></app-uploader>
                        </template>
                    </el-table-column>
                    <el-table-column prop="skuProperty" label="属性-属性值" min-width="210">
                        <template slot-scope="scope">
                            <div class="flex align-center flex-start" :class="{'margin_top_10': index > 0}" v-for="(item, index) of scope.row.skuProperty" :key="'shuxingzhi' + index">
                                <div class="text-ellipsis" style="min-width: 7em;word-break: keep-all;" :title="item.parentName">{{item.parentName}}：</div>
                                <div style="min-width: 7em;word-break: keep-all;">
                                    <el-select size="small" v-model="item.id" filterable :value-key="'name'" placeholder="请选择属性值" v-if="item.list" @change="changeSKUProperty($event, item, index, scope.$index)">
                                        <el-option v-for="(item, index) in item.list" :key="'shuxingzhiselect' + index" :label="item.name" :value="item.id"></el-option>
                                    </el-select>
                                    <div class="text-ellipsis" v-else :title="item.name">{{item.name}}</div>
                                </div>
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column prop="skuCostPrice" label="模型颜色" width="160">
                        <template slot-scope="scope">
                            <el-select size="small" v-model="scope.row.skuColor" filterable :value-key="'name'" placeholder="请选择模型颜色">
                                <el-option v-for="item in colorList" :key="'color' + item.id" :label="item.name" :value="item"></el-option>
                            </el-select>
                        </template>
                    </el-table-column>
                    <el-table-column prop="skuCostPrice" label="价格类型" width="160">
                        <template slot-scope="scope">
                            <el-select size="small" v-model="scope.row.skuType" filterable placeholder="请选择价格类型" @change="changeSKUType($event, scope.$index)">
                                <el-option v-for="item in priceList" :key="'pricetype' + item.value" :label="item.name" :value="item"></el-option>
                            </el-select>
                        </template>
                    </el-table-column>
                    <el-table-column prop="name" label="价格" width="260">
                        <template slot-scope="scope">
                            <div v-if="scope.row.skuPrice && scope.row.skuPrice.length">
                                <div class="flex align-center flex-start" :class="{'margin_top_10': typeIndex > 0}" v-for="(typeItem, typeIndex) in scope.row.skuPrice" :key="'typeItem' + typeIndex">
                                    <div style="width: 6em">{{typeItem.priceName}}：</div>
                                    <div>
                                        <el-input-number size="small" v-model.trim="typeItem.value" :placeholder="'请输入' + typeItem.priceName" :precision="2" :controls="false" :min="0" @keydown.native="inputNoneNumberUnpass"></el-input-number>
                                        <el-tooltip class="item" effect="dark" :content="typeItem.remark" placement="right">
                                        <i class="el-icon-question"></i>
                                        </el-tooltip>
                                    </div>
                                </div>
                            </div>
                            <div class="margin_top_10" v-if="scope.row.skuPrice && scope.row.skuPrice.length"><el-button size="mini" @click="copySkuPrice(scope.$index)">复制价格到全部SKU</el-button></div>
                        </template>
                    </el-table-column>
                    <el-table-column prop="name" label="库存" width="160">
                        <template slot-scope="scope">
                            <el-input-number size="small" v-model.trim="scope.row.skuQty" placeholder="请输入当前库存" :precision="0" :controls="false" :min="1" :max="1000000" :disabled="!!scope.row.id" @keydown.native="inputNoneNumberUnpass"></el-input-number>
                            <template v-if="scope.row.id">
                                <div class="flex align-center flex-start margin_top_10">
                                    <el-radio v-model="scope.row.isAddCount" :label="1">增加</el-radio>
                                    <el-input-number style="width: 49px" :controls="false" v-model.trim="scope.row.editAddCount" placeholder="请输入需要增减的库存" :precision="0" :min="0" :max="1000000" @keydown.native="inputNoneNumberUnpass" v-show="scope.row.isAddCount == 1"></el-input-number>
                                </div>
                                <div class="flex align-center flex-start margin_top_10">
                                    <el-radio v-model="scope.row.isAddCount" :label="2">减少</el-radio>
                                    <el-input-number style="width: 49px" :controls="false" v-model.trim="scope.row.editSubCount" placeholder="请输入需要增减的库存" :precision="0" :min="0" :max="1000000" @keydown.native="inputNoneNumberUnpass" v-show="scope.row.isAddCount == 2"></el-input-number>
                                </div>
                            </template>
                        </template>
                    </el-table-column>
                    <el-table-column prop="name" label="规格" width="240">
                        <template slot-scope="scope">
                            <div class="flex align-center flex-start">
                                <div>单位：</div>
                                <div>
                                    <el-input size="small" v-model.trim="scope.row.skuUnit" placeholder="请输入单位" maxlength="10" style="width: 130px"></el-input>
                                </div>
                            </div>
                            <div class="flex align-center flex-start margin_top_10">
                                <div>体积：</div>
                                <div>
                                    <el-input-number size="small" v-model.trim="scope.row.skuVolume" placeholder="请输入体积" :precision="2" :controls="false" :min="0" :max="9999" @keydown.native="inputNoneNumberUnpass"></el-input-number>
                                </div>
                                <div class="margin_left_6">m³</div>
                            </div>
                            <div class="flex align-center flex-start margin_top_10">
                                <div>重量：</div>
                                <div>
                                    <el-input-number size="small" v-model.trim="scope.row.skuWeight" placeholder="请输入重量" :precision="2" :controls="false" :min="0" :max="9999" @keydown.native="inputNoneNumberUnpass"></el-input-number>
                                </div>
                                <div class="margin_left_6">KG</div>
                            </div>
                            <div class="margin_top_10"><el-button size="mini" @click="copySkuRule(scope.$index)">复制规格到全部SKU</el-button></div>
                        </template>
                    </el-table-column>
                    <el-table-column prop="sizeType" label="尺码模板" width="160" v-if="isShowSize">
                        <template slot-scope="scope">
                            <el-select size="small" v-model="scope.row.sizeType" filterable placeholder="请选择尺码模板" @change="changeSizeType($event, scope.$index)">
                                <el-option v-for="item in sizeList" :key="item.id" :label="item.title" :value="item.id"></el-option>
                            </el-select>
                        </template>
                    </el-table-column>
                    <el-table-column prop="name" label="尺码数据" width="240" v-if="isShowSize">
                        <template slot-scope="scope">
                            <div v-if="scope.row.skuSize && scope.row.skuSize.length">
                                <div class="flex align-center flex-start" :class="{'margin_top_10': typeIndex > 0}" v-for="(typeItem, typeIndex) in scope.row.skuSize" :key="'typeItem' + typeIndex">
                                    <div style="width: 3em">{{typeItem.sizeName}}：</div>
                                  <div>
                                    <el-input-number size="small" v-model.trim="typeItem.value" :placeholder="'请输入' + typeItem.sizeName" :controls="false" :min="0" :max="9999.9" @keydown.native="inputNoneNumberUnpass" @change="saveNumber($event,scope.$index,typeIndex)"></el-input-number> cm
                                  </div>
<!--                                      <el-tooltip class="item" effect="dark" :content="typeItem.remark" placement="right">
                                        <i class="el-icon-question"></i>:precision="1"
                                        </el-tooltip>                                         -->
                                </div>
                            </div>
                            <!-- <div class="margin_top_10" v-if="scope.row.skuSize && scope.row.skuSize.length"><el-button size="mini" @click="copySkuPrice(scope.$index)">复制价格到全部SKU</el-button></div> -->
                        </template>
                    </el-table-column>
                    <el-table-column prop="skuState" label="上下架" width="80">
                        <template slot-scope="scope">
                            <el-switch v-model="scope.row.skuState"></el-switch>
                        </template>
                    </el-table-column>
                    <el-table-column prop="name" label="操作" width="80">
                        <template slot-scope="scope">
                            <el-button size="mini" type="danger" @click="removeSkuItem(scope.$index, scope.row.id)">删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>

                <div class="margin_top_10">
                    <el-button type="primary" @click="submit()" :loading="submitLoading" v-show="generateSKUDataList && generateSKUDataList.length">保存</el-button>
                    <el-button @click="customAddSKUItem()">新增SKU</el-button>
                </div>
            </el-col>
        </el-row>
        <el-dialog title="改价原因" :visible.sync="showPriceD" append-to-body @close="handelClose()">
            <el-form :label-width="'7em'">
                <span>检查到本次修改内容涉及到 价格更改 ，需要提交给财务进行审核，请填写改动原因：</span>
                <el-form-item label="改价原因" required>
                <el-input type="textarea" v-model="remark" placeholder="请输入改价原因" :rows="6" maxlength="200" show-word-limit></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="showPriceD = false">取 消</el-button>
                <el-button type="primary" @click="changePriceSubmit()">确 定</el-button>
            </div>
        </el-dialog>
        <attribute-list :visible.sync="isShowModal" :parent="showModalProperty" @selected="getSelectProperty"></attribute-list>
    </el-form>
</template>

<script>
import Setting from '@/settings';
import AppUploader from '@/components/AppUploader/index';
import AttributeList from '@/views/store-management/components/attributeList';
import * as defaultColor from '@/views/store-management/services/defaultColor';
import { GetSKUListById, InsertAndUpdateGoodsSKU, AddCustomStoreAttrItemValueOne, EditCustomStoreAttrItemOne, DeleteCustomStoreAttrItemOne,
DeleteCustomStoreAttrItemValueOne, InsertStoreItem, RemoveGoodsOneSKU, RemoveGoodsSelectSKU, GetRandomString, GetGoodBindedSize } from '@/views/store-management/services/index';
export default {
  props: ['storeId', 'storeNo', 'newAttr', 'storeAttrListAll', 'priceList', 'sizeList', 'detail', 'supplyId'],
  components: {
    AppUploader,
    AttributeList
  },
  data() {
    return {
        isCustom: false,
        loading: false,
        submitLoading: false,
        defaultPropertyDataList: [],
        checkPropertyDataList: [],
        choosePropertyDataList: [],
        myCustomPropertyDataList: [
            {
                id: '',
                name: '',
                code: '',
                isEdit: true,
                children: [{id: '', name: '', code: '', isEdit: true}]
            }
        ],
        generateSKUDataList: [],
        isShowModal: false,
        showModalProperty: null,
        fileFormat: ['jpg'],
        colorList: defaultColor.ColorList,
        isChangeAttr: false,
        hasGenerateId: false,
        imgBaseUrl: `${process.env.VUE_APP_FILE_URL}/`,
        randomString: '',
        newStoreNo: '',
        oldSkuDataIdsList: [],
        skuRandomList: [],
        maxAttrLength: 6,
        updateSKUTime: '',
        showPriceD: false,
        remark: '',
        isShowSize: false,
        sizeId: null,
        selectionSize: null
    }
  },
  watch: {
      newAttr: {
          immediate: true,
          handler(newValue, oldValue) {
            if (!newValue || !newValue.length) return;
            const newIds = newValue.map(item => item.propertyId).sort().toString();
            const oldIds = (oldValue && oldValue.length) ? oldValue.map(item => item.propertyId).sort().toString() : '';
            if (newIds == oldIds) return;
            this.defaultPropertyDataList = newValue.map(item => {
                return {
                    id: item.propertyId,
                    name: item.propertyName,
                    code: item.propertyNo,
                    status: item.status,
                    sort: item.sort,
                    children: []

                }
            }).sort((a, b) => a.sort - b.sort);
            this.choosePropertyDataList = JSON.parse(JSON.stringify(this.defaultPropertyDataList));
          }
      },
      storeId: {
          immediate: true,
          handler(newValue) {
              if (!newValue) return;
              if (this.hasGenerateId) return;
              GetSKUListById({id : newValue})
              .then(data => {
                  if (data && data.code == 200) {
                      setTimeout(() => {
                          this.setData(data.data);
                      }, 1000)
                  }
              })
          }
      },
      storeNo: {
          immediate: true,
          handler(newValue) {
              if (!newValue) return;
              this.randomString = newValue.substr(newValue.length - 6, newValue.length);
              this.newStoreNo = newValue.substr(0, newValue.length - 6);
          }
      },
      storeAttrListAll: {
          immediate: true,
          handler(newValue) {
              if (!newValue || !newValue.length) return;
              this.checkPropertyDataList = this.storeAttrListAll.map(item => {
                    return {
                        id: item.propertyId,
                        name: item.propertyName,
                        code: item.propertyCode,
                        status: item.status,
                        sort: item.sort,
                        children: []
                    }
                });
          }
      }
  },
  computed: {
      canBuildAttrLength() {
          return this.maxAttrLength - this.myCustomPropertyDataList.length;
      }
  },
  
  methods: {
    //   保留小数点后面一位
      saveNumber(currentValue,tableIndex,typeIndex) {
          console.log(currentValue)
         currentValue = ( parseInt( currentValue * 10) / 10 ).toFixed(1)
         this.generateSKUDataList[tableIndex].skuSize[typeIndex].value = currentValue
        //  return 
      },
    getSizeBinded() {
        this.sizeId = ''
        this.selectionSize = null
          GetGoodBindedSize({
              id: this.storeId
          }).then(data =>{
              if(data.code == 200) {
                this.isShowSize = JSON.parse(data.data.isBind);
                this.sizeId = data.data.id?data.data.id: null;
                this.selectionSize = data.data.selectionSize?JSON.parse(data.data.selectionSize): null;

              }
          })
    },
    handelClose() {
      this.showPriceD = false
    },
    inputSuppCode(scope) {
        scope.row.code = scope.row.code.replace(/[^\w\.\/]/ig,'').toUpperCase();
    },
    inputSuppCode1(val, data) {
        val = val.replace(/[^\w\.\/]/ig,'');
        data.code = val.toUpperCase();
    },
    changeOption(event) {
        this.isChangeAttr = true;
    },
    compareObject(a, b) {
                let result = false
                for(let i = 0;i<a.length;i++){
                  if(  a[i].value !=  b[i].value ){
                      result = true
                      break
                  }
                }
              return  result
        },
    async submit() {
        // 验证生成的sku列表数据
        if (!this.generateSKUDataList || !this.generateSKUDataList.length) {
            this.$message.warning('SKU列表不可为空!');
            return;
        }
        const validBoolean = this.generateSKUDataList.every(item => {
            if (!item.skuImg) {
                this.$message.warning('请上传SKU封面图片!');
                return false;
            }
            if (item.skuProperty.some(child => !child.id)) {
                this.$message.warning('请选择SKU属性值!');
                return false;
            }
            if (!item.skuType) {
                this.$message.warning('请选择SKU价格类型!');
                return false;
            }
            let costPrice = item.skuPrice.find(fi => fi.fieldName == 'costPrice'); // 采购价
            let supplyPrice = item.skuPrice.find(fi => fi.fieldName == 'supplyPrice'); // B端销售价
            let minPrice = item.skuPrice.find(fi => fi.fieldName == 'minPrice'); // 最低售价
            let suggestedPrice = item.skuPrice.find(fi => fi.fieldName == 'suggestedPrice'); // C端售价
            if (costPrice && !costPrice.value) {
                this.$message.warning('请输入' + costPrice.priceName + '!');
                return false;
            }
            if (supplyPrice && !supplyPrice.value) {
                this.$message.warning('请输入' + supplyPrice.priceName + '!');
                return false;
            }
            if (minPrice && !minPrice.value) {
                this.$message.warning('请输入' + minPrice.priceName + '!');
                return false;
            }
            if (suggestedPrice && !suggestedPrice.value) {
                this.$message.warning('请输入' + suggestedPrice.priceName + '!');
                return false;
            }
            // 前端写死的规则： C端售价 > 最低售价 > B端销售价 > 采购价
            if (suggestedPrice && minPrice && !(Number(suggestedPrice.value) >= Number(minPrice.value))) {
                this.$message.warning('C端售价应大于等于最低售价!');
                return false;
            }
            if (minPrice && supplyPrice && !(Number(minPrice.value) >= Number(supplyPrice.value))) {
                this.$message.warning('最低售价应大于等于B端销售价!');
                return false;
            }
            if (supplyPrice && costPrice && !(Number(supplyPrice.value) >= Number(costPrice.value))) {
                this.$message.warning('B端销售价应大于等于采购价!');
                return false;
            }
            if (!item.skuUnit) {
                this.$message.warning('请输入商品单位!');
                return false;
            }
            return true;
        })
        if (!validBoolean) return;
        let skuList = JSON.parse(localStorage.getItem('skuList'))

        let finderSku = skuList.map((item,index) => {
            let finder = false
           this.generateSKUDataList.map(child => {
                if(child.id == item.id) {
                    if(child.skuType.value == item.skuType.value) {
                       finder =  this.compareObject(child.skuPrice, item.skuPrice)
                    }else {
                        finder = true
                    }
                    return finder
                 }
            })
            return finder
        })
        if(finderSku.some(item => item == true)) {
            this.showPriceD = true
            return
        }
        this.submitLoading = true;
        const queryData = this.generateSKUDataList.map(item => {
            console.log(item)
            let finder = item.skuSize ? item.skuSize.some(child => child.value) : false
            const newItem = {
                id: item.id,
                skuNo: item.skuNo, // sku编码
                goodsId: this.storeId, // 商品id
                imgUrl: item.skuImg, // sku图片
                modelColor: item.skuColor ? item.skuColor.name : '',
                modelColorId: item.skuColor ? item.skuColor.id : '',
                priceTemplateId: item.skuType.value,
                sizeTemplateId: item.sizeType,
                selectionSize: item.skuSize?JSON.stringify(item.skuSize):null,
                isSize: !item.sizeType ? 0 : finder == true > 0 ? 2 : 1,
                qty: item.id ? (item.isAddCount == '1' ? item.editAddCount : -item.editSubCount) : item.skuQty, // 库存
                shelvesStatus: item.skuState ? 1 : 0, // 上下架状态：0下架，1上架,2待售
                unit: item.skuUnit, // 单位
                barNumber: item.skuCode, // 商品条码
                articleNumber: item.skuSupplyNo, //供应商货号
                weight: item.skuWeight, // 重量
                volume: item.skuVolume, // 体积
                propertyRelationsList: item.skuProperty.map(child => {
                    return {
                        property: child.parentName, // 属性名
                        propertyId: child.parentId, // 属性名id
                        propertyValue: child.name, // 属性值
                        valueId: child.id // 属性值id
                    }
                }) // 属性-属性值
            };
            item.skuPrice.forEach(childItem => {
                newItem[childItem.fieldName] = childItem.value;
            })
            return newItem;
        })
        // 对比需要删除的sku
        if (this.oldSkuDataIdsList && this.oldSkuDataIdsList.length && !this.hasGenerateId) {
            const newIds = this.generateSKUDataList.filter(f => f.id).map(q => q.id);
            let diff = this.oldSkuDataIdsList.filter(val => { return newIds.indexOf(val) === -1 })
            if (diff && diff.length) {
                let deleteData = await RemoveGoodsSelectSKU({targetIds: diff.join(',')});
                if (deleteData.code != 200) {
                    this.$message.error('SKU批量删除失败:' + deleteData.msg);
                    this.submitLoading = false;
                    return;
                }
            }
        }
        // 需要判断是否是
        console.log(queryData)
        InsertAndUpdateGoodsSKU({ goodsId: this.storeId, goodsSkuList: queryData })
        .finally(() => this.submitLoading = false)
        .then(data => {
            if (data.code == 200) {
                this.$message.success('保存成功!');
                this.submitLoading = true;
                this.updateSKUTime = moment().format('YYYY-MM-DD HH:mm:ss');
                GetSKUListById({id : this.storeId})
                .finally(() => this.submitLoading = false)
                .then(data => {
                    if (data.code == 200) {
                        this.setData(data.data);
                    }
                })
            } else {
                this.$message.error('保存失败!');
            }
        })
    },
    async changePriceSubmit() {
        if(this.remark == '') {
            this.$message.warning('请填写改价原因！')
            return
        }

        this.submitLoading = true;
        const queryData = this.generateSKUDataList.map(item => {
            let finder = item.skuSize ? item.skuSize.some(child => child.value) : false
            const newItem = {
                id: item.id,
                skuNo: item.skuNo, // sku编码
                goodsId: this.storeId, // 商品id
                imgUrl: item.skuImg, // sku图片
                modelColor: item.skuColor ? item.skuColor.name : '',
                modelColorId: item.skuColor ? item.skuColor.id : '',
                priceTemplateId: item.skuType.value,
                sizeTemplateId: item.sizeType,
                selectionSize: item.skuSize?JSON.stringify(item.skuSize):null,
                isSize: !item.sizeType ? 0 : finder == true > 0 ? 2 : 1,
                qty: item.id ? (item.isAddCount == '1' ? item.editAddCount : -item.editSubCount) : item.skuQty, // 库存
                shelvesStatus: item.skuState ? 1 : 0, // 上下架状态：0下架，1上架,2待售
                unit: item.skuUnit, // 单位
                barNumber: item.skuCode, // 商品条码
                articleNumber: item.skuSupplyNo, //供应商货号
                weight: item.skuWeight, // 重量
                volume: item.skuVolume, // 体积
                propertyRelationsList: item.skuProperty.map(child => {
                    return {
                        property: child.parentName, // 属性名
                        propertyId: child.parentId, // 属性名id
                        propertyValue: child.name, // 属性值
                        valueId: child.id // 属性值id
                    }
                }) // 属性-属性值
            };
            item.skuPrice.forEach(childItem => {
                newItem[childItem.fieldName] = childItem.value;
            })
            return newItem;
        })
        // 对比需要删除的sku
        if (this.oldSkuDataIdsList && this.oldSkuDataIdsList.length && !this.hasGenerateId) {
            const newIds = this.generateSKUDataList.filter(f => f.id).map(q => q.id);
            let diff = this.oldSkuDataIdsList.filter(val => { return newIds.indexOf(val) === -1 })
            if (diff && diff.length) {
                let deleteData = await RemoveGoodsSelectSKU({targetIds: diff.join(',')});
                if (deleteData.code != 200) {
                    this.$message.error('SKU批量删除失败:' + deleteData.msg);
                    this.submitLoading = false;
                    return;
                }
            }
        }
        // 需要判断是否是
        InsertAndUpdateGoodsSKU({ goodsId: this.storeId, goodsSkuList: queryData,remark: this.remark })
        .finally(() => this.submitLoading = false)
       .then(data => {
            if (data.code == 200) {
                this.$message.success('保存成功!');
                this.submitLoading = true;
                this.showPriceD = false
                this.updateSKUTime = moment().format('YYYY-MM-DD HH:mm:ss');
                GetSKUListById({id : this.storeId})
                .finally(() => this.submitLoading = false)
                .then(data => {
                    if (data.code == 200) {
                        this.setData(data.data);
                    }
                })
            } else {
                this.$message.error('保存失败!');
            }
        })
    },
    // 变更属性值时修改编码以及赋值数据
     changeSKUProperty(value, node, index, rowIndex) {
        const finder = node.list.find(item => item.id == value);
        node.name = finder.name;
        node.code = finder.code;
        const buildCoder = Array.from({length:4}, (value, index) => this.defaultPropertyDataList.find(de => de.sort == index + 1));

        const codeNo = buildCoder.map(bc => {
            if (bc) {
                const builder = this.generateSKUDataList[rowIndex].skuProperty.find(it => it.parentId == bc.id);
                return this.autoComplateString(builder.code, 3);
            } else {
                return this.autoComplateString('', 3);
            }
        }).join('');

        if (this.generateSKUDataList[rowIndex].skuProperty.every(item => item.id)) {
            this.returnSkuNo(this.newStoreNo + codeNo, rowIndex);
        }
    },
    // 新建sku
    customAddSKUItem() {
        if (!this.validSKUForm()) return;
        // const myPropertyDataList = this.defaultPropertyDataList.concat(this.choosePropertyDataList);
        const myPropertyDataList = this.choosePropertyDataList;
        let newList = myPropertyDataList.map(item => {
            return {
                id: '',
                name: '',
                code: '',
                list: item.children.map(child => child),
                parentId: item.id,
                parentName: item.name,
                parentCode: item.code
            }
        }).concat(this.myCustomPropertyDataList.filter(item => item.id).map(item => {
            return {
                id: '',
                name: '',
                code: '',
                list: item.children.map(child => child),
                parentId: item.id,
                parentName: item.name,
                parentCode: item.code
            }
        }));

        this.generateSKUDataList.push({
            id: '',
            skuNo: '',
            skuCode: '',
            skuImg: '',
            skuType: null,
            sizeType: this.sizeId?this.sizeId: null,
            skuPrice: [],
            skuSize: this.selectionSize?this.selectionSize:null,
            skuQty: 0,
            skuColor: null,
            skuState: true,
            skuProperty: newList,
            skuSupplyNo: '',
            skuUnit: '',
            skuVolume: 0,
            skuWeight: 0
        });
    },
    changeSKUType(value, index) {
        this.generateSKUDataList[index].skuPrice = JSON.parse(JSON.stringify(value.children));
    },
    changeSizeType(value, index) {
        const list = this.sizeList.find(item => (
            item.id == value
        ));
        this.generateSKUDataList[index].skuSize = JSON.parse(list.selectionSize)
    },
    // 回调
    getSelectProperty(list) {
        this.showModalProperty.children = list;
    },
    addPropertyChild(rowData) {
        this.showModalProperty = rowData;
        this.isShowModal = true;
    },
    addDefaultPropertyChild(rowData) {
        this.showModalProperty = rowData;
        this.isShowModal = true;
    },
    removeProperty(index) {
        this.choosePropertyDataList.splice(index, 1);
    },
    removeDafaultProperty(index) {
        this.defaultPropertyDataList.splice(index, 1);
    },
    // 图片上传成功的回调
    skuImgChange(event, index) {
        this.generateSKUDataList[index].skuImg = event[0] ? event[0].fileUrl : '';
    },
    // 添加单个属性对象
    addOnePropertyItem() {
        this.myCustomPropertyDataList.push({
            id: '',
            name: '',
            code: '',
            isEdit: true,
            children: [{id: '', name: '', code: '', isEdit: true}]
        });
    },
    saveOnePropertyItemCopy(index) {
        if (!this.myCustomPropertyDataList[index].name) {
            this.$message.warning('请输入属性名称!');
            return;
        }
        const isAllName = this.myCustomPropertyDataList[index].children.every(child => !!child.name);
        if (!isAllName) {
            this.$message.warning('请输入属性值名称!');
            return;
        }
        this.submitLoading = true;
        if (this.myCustomPropertyDataList[index].id) {
            EditCustomStoreAttrItemOne({
                id: this.myCustomPropertyDataList[index].id,
                propertyName: this.myCustomPropertyDataList[index].name,
                propertyNo: this.myCustomPropertyDataList[index].code,
                propertyValuesList: this.myCustomPropertyDataList[index].children.map(child => {
                    return { valueName: child.name, valueNo: child.code ,id: child.id };
                })
            })
            .finally(() => this.submitLoading = false)
            .then(data => {
                if (data.code == 200) {
                    this.$message.success('保存成功!');
                    // this.myCustomPropertyDataList[index].isEdit = false;
                    this.myCustomPropertyDataList[index].code = data.data.propertyNo
                    this.myCustomPropertyDataList[index].children = data.data.propertyValuesList.map(pro => {
                        return {
                            id: pro.id,
                            name: pro.valueName,
                            code: pro.valueNo,
                            // isEdit: false
                        }
                    })
                } else {
                    this.$message.error('保存失败!');
                }
            })
            return;
        }
        this.isChangeAttr = true;
        AddCustomStoreAttrItemValueOne({
            propertyName: this.myCustomPropertyDataList[index].name,
            propertyNo: this.myCustomPropertyDataList[index].code,
            goodsId: this.storeId,
            status: 1,
            propertyValuesList: this.myCustomPropertyDataList[index].children.map(child => {
                return { valueName: child.name, valueNo: child.code, id: child.id };
            })
        })
        .finally(() => this.submitLoading = false)
        .then(data => {
            if (data.code == 200) {
                this.$message.success('保存成功!');
                this.myCustomPropertyDataList[index].code = data.data.propertyNo
                this.myCustomPropertyDataList[index].id = data.data.id;
                // 需要将所有的属性值id填充
                this.myCustomPropertyDataList[index].children = data.data.propertyValuesList.map(pro => {
                    return {
                        id: pro.id,
                        name: pro.valueName,
                        code: pro.valueNo,
                    }
                })
            } else {
                this.$message.error('保存失败!');
            }
        })
    },
    removeOnePropertyItem(index) {
        if (this.myCustomPropertyDataList[index].id) {
            this.$confirm('此操作将永久删除该属性, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                showClose: false,
                closeOnClickModal: false,
                closeOnPressEscape: false,
                type: 'warning',
                beforeClose: (action, instance, done) => {
                if (action === 'confirm') {
                    instance.confirmButtonLoading = true;
                    DeleteCustomStoreAttrItemOne({ targetIds: this.myCustomPropertyDataList[index].id })
                    .then(data => {
                        instance.confirmButtonLoading = false;
                        if (data.code == 200) {
                            this.$message.success('删除成功!');
                            this.isChangeAttr = true;
                            done();
                        } else {
                        this.$message.success('删除失败!');
                        }
                    })
                    .catch(error => {
                        instance.confirmButtonLoading = false;
                    })
                } else {
                    done();
                }
                }
            }).then(() => {
                this.myCustomPropertyDataList.splice(index, 1);
            })
            return;
        }
        this.myCustomPropertyDataList.splice(index, 1);
    },
    // 添加单个属性值对象
    addOnePropertyValueItem(index) {
        this.myCustomPropertyDataList[index].children.push({
            id: '',
            name: '',
            code: '',
            // isEdit: true
        });
    },
    removeOnePropertyValueItem(index, childIndex) {
        if (this.myCustomPropertyDataList[index].children[childIndex].id) {
            this.$confirm('此操作将永久删除该属性, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                showClose: false,
                closeOnClickModal: false,
                closeOnPressEscape: false,
                type: 'warning',
                beforeClose: (action, instance, done) => {
                if (action === 'confirm') {
                    instance.confirmButtonLoading = true;
                    DeleteCustomStoreAttrItemValueOne({ targetIds: this.myCustomPropertyDataList[index].children[childIndex].id })
                    .then(data => {
                        instance.confirmButtonLoading = false;
                        if (data.code == 200) {
                            this.$message.success('删除成功!');
                            done();
                        } else {
                        this.$message.success('删除失败!');
                        }
                    })
                    .catch(error => {
                        instance.confirmButtonLoading = false;
                    })
                } else {
                    done();
                }
                }
            }).then(() => {
                this.myCustomPropertyDataList.splice(index, 1);
            })
            return;
        }
        this.myCustomPropertyDataList[index].children.splice(childIndex, 1);
    },
    // 是否可以生成sku
    validIsCanGenerrate() {
        if (!this.validSKUForm()) return;
        if (this.detail && !this.$parent.$parent.justGenerateId && !this.hasGenerateId && this.isChangeAttr) {
            this.$msgbox({
                title: '提示',
                message: '商品属性发生了改变，将为您生成新的商品!',
                showCancelButton: false,
                confirmButtonText: '确定',
                beforeClose: (action, instance, done) => {
                    if (action === 'confirm') {
                        instance.confirmButtonLoading = true;
                        this.functionIsGetRandom(this.detail.supplierId)
                            .then(data => {
                                const newGoodsNo = this.newStoreNo + data;
                                InsertStoreItem({
                                    mchId: this.detail.mchId,
                                    creatorId: this.detail.creatorId,
                                    mchType: (this.$store.getters.userInfo && JSON.parse(this.$store.getters.userInfo).userType == 1) ? 1 : 0, // 商户类型 默认 0 平台  1 普通商户
                                    isEntity: this.detail.isEntity, // 是否实物商品 0实物商品 1虚拟商品
                                    title: this.detail.title, // 标题
                                    categoryId: this.detail.categoryId, // 商品类目id
                                    firstCategoryId: this.detail.firstCategoryId, // 商品一级类目id
                                    secondCategoryId: this.detail.secondCategoryId, // 商品二级类目id
                                    thirdCategoryId: this.detail.thirdCategoryId, // 商品三级类目id
                                    brandId: this.detail.brandId, // 品牌
                                    supplierId: this.detail.supplierId, // 供应商id
                                    goodsNo: newGoodsNo, // 商品编码
                                    taxNumber: this.detail.taxNumber, // 商品税号
                                    taxId: this.detail.taxId, // 商品税率id
                                    taxRate: this.detail.taxRate, //商品税率
                                    articleNumber: this.detail.articleNumber, // 商品供应商货号
                                    subtitle: this.detail.subtitle, // 商品副标题
                                    surfaceImg: this.detail.surfaceImg, // 封面图
                                    goodsFileList: this.detail.goodsFileList.map(item => {
                                        return {
                                            fileType: item.fileType,
                                            fileUrl: item.fileUrl,
                                            sort: item.sort
                                        }
                                    }),
                                    introduction: this.detail.introduction // 商品详情
                                })
                                .finally(() => instance.confirmButtonLoading = false)
                                .then(data => {
                                    if (data.code == 200) {
                                        this.$emit('update:storeId', data.data.id);
                                        this.$emit('update:storeNo', newGoodsNo);
                                        this.isChangeAttr = false;
                                        this.hasGenerateId = true;
                                        done();
                                    } else {
                                        this.$message.error(data.msg);
                                    }
                                })
                            })
                            .catch(error => {
                                instance.confirmButtonLoading = false;
                            })
                    } else {
                        done();
                    }
                }
            })
            .then(() => {
                this.autoGenerateSKU();
            })
        } else {
            this.autoGenerateSKU();
        }
    },
    // 自动生成SKU（core）
    autoGenerateSKU() {
        // 重置存储更新的随机码，以防止重复
        this.skuRandomList = [];
        const buildCoder = Array.from({length:4}, (value, index) => this.defaultPropertyDataList.find(de => de.sort == index + 1));

        this.loading = true;
        // 扁平化属性值数组
        let list = [];
        const myPropertyDataList = this.choosePropertyDataList;
        myPropertyDataList.forEach(item => {
            const childList = item.children.map(childItem => {
                childItem.parentId = item.id;
                childItem.parentName = item.name;
                childItem.parentCode = item.code;
                return childItem;
            });
            list.push(childList);
        });
        if (this.isCustom) {
            this.myCustomPropertyDataList.forEach(item => {
                const childList = item.children.map(childItem => {
                    childItem.parentId = item.id;
                    childItem.parentName = item.name;
                    childItem.parentCode = item.code;
                    return childItem;
                });
                list.push(childList);
            });
        }

        this.generateSKUDataList = this.myCartesianFun(...list).map((item, index) => {
            const codeNo = buildCoder.map(bc => {
                if (bc) {
                    const builder = item.find(it => it.parentId == bc.id);
                    if (builder) {
                        return this.autoComplateString(builder.code, 3);
                    } else {
                        return this.autoComplateString('', 3);
                    }
                } else {
                    return this.autoComplateString('', 3);
                }
            }).join('');
            let sizeType = this.sizeId ? this.sizeId: null;
            let selectionSize = this.selectionSize?this.selectionSize: null
            // let sizeList = this.sizeList.find(child => child.id == this.sizeId);

            const newitem = {
                id: '',
                skuNo: '',
                skuCode: '',
                skuImg: '',
                skuType: null,
                sizeType: sizeType,
                skuPrice: [],
                skuSize: selectionSize,
                skuQty: 0,
                skuColor: null,
                skuState: true,
                skuProperty: item,
                skuSupplyNo: '',
                skuUnit: '',
                skuVolume: 0,
                skuWeight: 0
            }

            this.returnSkuNo(this.newStoreNo + codeNo, index);

            return JSON.parse(JSON.stringify(newitem));
        })
        this.loading = false;
    },
    returnSkuNo(oldNo, index) {
        this.functionIsGetRandom(this.supplyId)
            .then(data => {
                if (this.skuRandomList.includes(data)) {
                    this.returnSkuNo(oldNo, index);
                } else {
                    this.skuRandomList.push(data);
                    this.generateSKUDataList[index].skuNo = oldNo + data;
                }
            })
    },
    copySkuSupplyNo(index) {
        this.$confirm('将复制该供应商货号到全部SKU, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
            beforeClose: (action, instance, done) => {
                if (action === 'confirm') {
                    instance.confirmButtonLoading = true;
                    this.generateSKUDataList.forEach(item => {
                        const defaultData = JSON.parse(JSON.stringify(this.generateSKUDataList[index]));
                        item.skuSupplyNo = defaultData.skuSupplyNo;
                        // item.skuPrice = defaultData.skuPrice;
                    })
                    instance.confirmButtonLoading = false;
                    done();
                    this.$message.success('应用成功!');
                } else {
                    done();
                }
            }
        });
    },
    copySkuPrice(index) {
        this.$confirm('将复制该SKU价格到全部SKU, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
            beforeClose: (action, instance, done) => {
                if (action === 'confirm') {
                    instance.confirmButtonLoading = true;
                    this.generateSKUDataList.forEach(item => {
                        const defaultData = JSON.parse(JSON.stringify(this.generateSKUDataList[index]));
                        item.skuType = defaultData.skuType;
                        item.skuPrice = defaultData.skuPrice;
                    })
                    instance.confirmButtonLoading = false;
                    done();
                    this.$message.success('应用成功!');
                } else {
                    done();
                }
            }
        });
    },
    copySkuRule(index) {
        this.$confirm('将复制该SKU规格到全部SKU, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
            beforeClose: (action, instance, done) => {
                if (action === 'confirm') {
                    instance.confirmButtonLoading = true;
                    this.generateSKUDataList.forEach(item => {
                        const defaultData = JSON.parse(JSON.stringify(this.generateSKUDataList[index]));
                        item.skuUnit = defaultData.skuUnit;
                        item.skuWeight = defaultData.skuWeight;
                        item.skuVolume = defaultData.skuVolume;
                    })
                    instance.confirmButtonLoading = false;
                    done();
                    this.$message.success('应用成功!');
                } else {
                    done();
                }
            }
        });
    },
    removeSkuItem(index, rowId) {
        this.$confirm('将删除该SKU, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            showClose: false,
            closeOnClickModal: false,
            closeOnPressEscape: false,
            type: 'warning',
            beforeClose: (action, instance, done) => {
                if (action === 'confirm') {
                    if (!rowId) {
                        done();
                        return;
                    }
                    instance.confirmButtonLoading = true;
                    RemoveGoodsOneSKU({ id: rowId })
                    .then(data => {
                        instance.confirmButtonLoading = false;
                        if (data.code == 200) {
                            // 本地删除
                            this.oldSkuDataIdsList = this.oldSkuDataIdsList.filter(id => id != rowId);
                            done();
                        } else {
                            this.$message.error('删除失败!');
                        }
                    })
                    .catch(error => {
                        instance.confirmButtonLoading = false;
                    })
                } else {
                    done();
                }
            }
        }).then(() => {
            this.generateSKUDataList.splice(index, 1);
            this.$message.success('删除成功!');
        })
    },
    myCartesianFun(...args) {
        if (!args || !args.length) return [];
        if (args.length < 2) {
            const list = [];
            args[0].forEach(item => {
                list.push([item]);
            })
            return list;
        };
        const list = [];
        args[0].forEach(item => {
            args[1].forEach(otherItem => {
                if (item.length) {
                    list.push([...item, otherItem]);
                } else {
                    list.push([item, otherItem]);
                }
            })
        })
        if (args.length > 2) {
            const newList = [list].concat(args.splice(2));
            return this.myCartesianFun(...newList);
        }
        return list;
    },
    // 验证数据完整性
    validSKUForm() {
        // const myPropertyDataList = this.defaultPropertyDataList.concat(this.choosePropertyDataList);
        const myPropertyDataList = this.choosePropertyDataList;
        if (!this.isCustom) {
            if (!myPropertyDataList || !myPropertyDataList.length) {
                this.$message.warning('请选择商品属性!');
                return false;
            }
            const allHasChild = myPropertyDataList.every(item => item.children && item.children.length);
            if (!allHasChild) {
                this.$message.warning('请选择商品属性值!');
                return false;
            }
        } else {
            if ((!myPropertyDataList || !myPropertyDataList.length) && (!this.myCustomPropertyDataList || !this.myCustomPropertyDataList.length)) {
                this.$message.warning('请选择商品属性或添加自定义属性!');
                return false;
            }
            // 如果选择了，验证属性值
            if (myPropertyDataList.length) {
                const allHasChild = myPropertyDataList.every(item => item.children && item.children.length);
                if (!allHasChild) {
                    this.$message.warning('请选择商品属性值!');
                    return false;
                }
            }
            if (this.myCustomPropertyDataList.length) {
                const allInput = this.myCustomPropertyDataList.every(item => item.name && item.code);
                if (!allInput) {
                    this.$message.warning('自定义属性填写不完整!');
                    return false;
                }
                // const allInputValid = this.myCustomPropertyDataList.every(item => (Setting.expression[0].value).test(item.code));
                // if (!allInputValid) {
                //     this.$message.warning('自定义属性编码只能输入字母和数字!');
                //     return false;
                // }
                const allItemSaveValid = this.myCustomPropertyDataList.every(item => item.id);
                if (!allItemSaveValid) {
                    this.$message.warning('请先保存自定义属性!');
                    return false;
                }
                const allHasChild = this.myCustomPropertyDataList.every(item => item.children && item.children.length);
                if (!allHasChild) {
                    this.$message.warning('请添加自定义属性的属性值!');
                    return false;
                }
                const allChildInput = this.myCustomPropertyDataList.every(item => item.children.every(childItem => childItem.name && childItem.code));
                if (!allChildInput) {
                    this.$message.warning('自定义属性的属性值填写不完整!');
                    return false;
                }
                const allChildInputValid = this.myCustomPropertyDataList.every(item => item.children.every(childItem => (Setting.expression[0].value).test(childItem.code)));
                if (!allChildInputValid) {
                    this.$message.warning('自定义属性的属性值编码只能输入字母和数字!');
                    return false;
                }
                // const allItemValueSaveValid = this.myCustomPropertyDataList.every(item => item.children.every(childItem => childItem.id));
                // if (!allItemValueSaveValid) {
                //     this.$message.warning('请先保存自定义属性中的属性值!');
                //     return false;
                // }
            }
        }
        return true;
    },
    setData(value) {
        let isUpdate;
        if (this.detail) {
            if (this.detail.updateTime && !moment('2021-04-30 11:00:00').isBefore(this.detail.updateTime)) {
                if (this.updateSKUTime && moment('2021-04-30 11:00:00').isBefore(this.updateSKUTime)) {
                    isUpdate = false;
                } else {
                    isUpdate = true;
                }
            } else {
                isUpdate = false;
            }
        } else {
            isUpdate = false;
        }
        const buildCoder = Array.from({length:4}, (value, index) => this.defaultPropertyDataList.find(de => de.sort == index + 1));

        if (value.propertyList && value.propertyList.length) {
            this.defaultPropertyDataList = value.propertyList.filter(item => !item.isPrivate && item.sort).map(item => {
                const newItem = {
                    id: item.propertyId,
                    name: item.property,
                    code: item.code,
                    sort: item.sort,
                    children: item.valueList.map(child => {
                        return {
                            id: child.valueId,
                            name: child.propertyValue,
                            code: child.code
                        }
                    })
                };
                return newItem;
            }).sort((a, b) => a.sort - b.sort);

            this.choosePropertyDataList = value.propertyList.filter(item => !item.isPrivate && !item.sort).map(item => {
                const newItem = {
                    id: item.propertyId,
                    name: item.property,
                    code: item.code,
                    sort: item.sort,
                    // isEdit: false,
                    children: item.valueList.map(child => {
                        return {
                            id: child.valueId,
                            // isEdit: false,
                            name: child.propertyValue,
                            code: child.code
                        }
                    })
                };
                // 判断是否存在于所有的属性值中
                const finder = this.checkPropertyDataList.find(fi => fi.id == newItem.id);
                if (!finder) {
                    this.checkPropertyDataList.unshift({
                        ...newItem,
                        status: 0
                    })
                }
                return newItem;
            });

            this.choosePropertyDataList = this.defaultPropertyDataList.concat(this.choosePropertyDataList);

            this.myCustomPropertyDataList = value.propertyList.filter(item => item.isPrivate).map(item => {
                return {
                    id: item.propertyId,
                    name: item.property,
                    code: item.code,
                    isEdit: false,
                    children: item.valueList.map(child => {
                        return {
                            id: child.valueId,
                            isEdit: false,
                            name: child.propertyValue,
                            code: child.code
                        }
                    })
                }
            });

            this.isCustom = !!(this.myCustomPropertyDataList.length);

            if (!this.myCustomPropertyDataList.length) {
                this.addOnePropertyItem();
            }
        }
        this.oldSkuDataIdsList = value.skuList.map(item => item.id);
        this.generateSKUDataList = value.skuList.map((item, index) => {
            const codeNo = buildCoder.map(bc => {
                if (bc) {
                    const builder = item.propertyList.find(it => it.propertyId == bc.id);
                    if (builder) {
                        return this.autoComplateString(builder.code, 3);
                    } else {
                        return this.autoComplateString('', 3);
                    }
                } else {
                    return this.autoComplateString('', 3);
                }
            }).join('');
            let skuType = this.priceList.find(child => child.value == item.priceTemplateId);
            // this.sizeList.find(child => child.id == item.sizeTemplateId)
            let sizeType = item.sizeTemplateId ? item.sizeTemplateId: this.sizeId? this.sizeId : null;
            console.log(this.selectionSize)
            let sizeList = item.selectionSize ? JSON.parse(item.selectionSize) : this.selectionSize? this.selectionSize: null;
            if (!skuType) {
                skuType = this.priceList[0];
            }
            //    let sizeList = item.selectionSize ? item.selectionSize : this.sizeList.find(child => child.id == sizeType);
            const newskuType = JSON.parse(JSON.stringify(skuType));
            console.log('gefghrhrgh',typeof(sizeList))
            const newsizeType = sizeList?JSON.parse(JSON.stringify(sizeList)): null;

            const newItem = {
                id: item.id,
                skuNo: '',
                skuCode: item.barNumber,
                skuSupplyNo: item.articleNumber,
                skuImg: item.imgUrl,
                skuType: newskuType,
                sizeType: sizeType,
                skuPrice: newskuType.children.map(child => {
                    child.value = item[child.fieldName];
                    return child;
                }),
                skuSize: newsizeType ? newsizeType : null,
                skuQty: item.qty,
                skuColor: item.modelColor ? { id: item.modelColorId, name: item.modelColor } : null,
                skuState: item.shelvesStatus == 1,
                skuProperty: item.propertyList.map(child => {
                    return {
                        parentId: child.propertyId,
                        parentName: child.property,
                        id: child.valueId,
                        name: child.propertyValue
                    }
                }),
                skuUnit: item.unit,
                skuVolume: item.volume,
                skuWeight: item.weight,

                isAddCount: null,
                editAddCount: 0,
                editSubCount: 0
            }
             
            if (isUpdate) {
                this.returnSkuNo(this.newStoreNo + codeNo, index);
            } else {
                newItem.skuNo = item.skuNo;
            }

            return newItem;
        });
        console.log('jdfhwldfhdl',this.generateSKUDataList)
        localStorage.setItem('skuList', JSON.stringify(this.generateSKUDataList))
        if ((!value.propertyList || !value.propertyList.length) && (!value.skuList || !value.skuList.length)) {
            this.$parent.$parent.justGenerateId = true;
        }
    },
    functionIsGetRandom(id) {
        return new Promise((resolve, reject) => {
            GetRandomString({id})
            .then(data => {
                if (data.code == 200 && data.data) {
                    resolve(data.data);
                } else {
                    reject(data.msg);
                }
            })
            .catch(error => {
                reject(error);
            })
        })
    }
  },
  updated() {
    this.$nextTick(() => {
      const numberInputList = document.querySelectorAll('.el-input-number input.el-input__inner');
      numberInputList.forEach(item => {
        item.type = 'number';
      })
    })
  },
  mounted() {
      this.getSizeBinded()
  },
}
</script>

<style lang="scss" scoped>
.width_1000 {
    max-width: 1000px;
}

.custom_attribute {
    // max-height: 480px;
    // overflow-y: auto;

    .custom_attribute__item {
        padding: 20px;
        margin-bottom: 15px;
        background: #ffffff;
        border: 1px solid #e4e7ed;
        border-radius: 5px;
        box-shadow: 0px 2px 12px 0px rgba(0,0,0,0.06);

        &:last-child {
            margin-bottom: 0;
        }
    }
}

::v-deep .el-input-number .el-input__inner {
    text-align: left;
    line-height: 1px!important;
}
</style>
